// Allow :active styles to work in your CSS on a page in Mobile Safari
document.addEventListener('touchstart', function() {}, true);

// 微信桥接口就绪回调
function wxReady(callback) {
    if (window.WeixinJSBridge) {
        callback && callback();
    } else {
        var _timeout_WX_regist = setTimeout(function() {
            if (window.WeixinJSBridge) {
                callback && callback();
            }
        }, 1000);
        document.addEventListener("WeixinJSBridgeReady", function() {
            clearTimeout(_timeout_WX_regist);
            callback && callback();
        });
    }
}

$(function() {

    // 微信分享相关
    var title =document.title,
        _desc = $.trim($('.custom-richtext:eq(0)').text()),
        desc = _desc ? _desc.substring(0, 80) : title,
        link =  document.documentURI,
        img = $('.content img')[0],
        kdtId = 0,
        shop = 'shop' + (192168 + kdtId);

    // alert('1:' + link);

    // 如果是微信登录态地址，则进行匹配处理
    if (link.indexOf('open.weixin.qq.com') !== -1) {
        link = decodeURIComponent(link);

        var temp = link.match(/redirect_uri\=(.*?)[\&|\$]/i);
        if (temp.length > 1 && temp[1].indexOf('/x/') === -1) {
            temp = link.match(/state=(.*?)[\#|\&|\$]/i);
        }
        if (temp.length > 1) {
            link = temp[1];
        } else {
            link = false;
        }
    }

    // alert('2:' + link);

    // 能获取到 kdt_id 则替换为 shop 类型地址
    if (kdtId > 0) {
        link = link.replace('wap', shop);
    }

    // alert('3:' + link);

    // 获取页面上的图片
    var imgUrl = '';
    if (img) {
        imgUrl = img.getAttribute('src') || img.getAttribute('data-src') || '';
    }

    wxReady(function() {

        var wxData = {
            'title': title,
            'link': link,
            'desc': desc,
            'img_url': imgUrl,
            'img_width': '200',
            'img_height': '200'
        };

        // alert('4:' + JSON.stringify(wxData));

        WeixinJSBridge.on('menu:share:timeline', function(argv) {
            // alert(JSON.stringify(argv));

            WeixinJSBridge.invoke('shareTimeline', wxData, function(res) {
                // alert(JSON.stringify(res));
            });
        });

        WeixinJSBridge.on('menu:share:facebook', function(argv) {
            // alert(JSON.stringify(argv));

            WeixinJSBridge.invoke('shareTimeline', wxData, function(res) {
                // alert(JSON.stringify(res));
            });
        });

        WeixinJSBridge.on('menu:share:appmessage', function(argv) {
            // alert(JSON.stringify(argv));

            WeixinJSBridge.invoke('sendAppMessage', wxData, function(res) {
                // alert(JSON.stringify(res));
            });
        });

        var wbData = {
            'content': title,
            'link': link,
            'img_url': imgUrl
        };
        WeixinJSBridge.on('menu:share:weibo', function(argv) {
            // alert(JSON.stringify(argv));

            WeixinJSBridge.invoke('shareWeibo', wbData, function(res) {
                // alert(JSON.stringify(res));
            });
        });

    });

});


// 需要用户再次确认
function needConfirm(msg, yesClk, noClk) {

    var result = window.confirm(msg);

    if (result) {
        if (yesClk && typeof yesClk === 'function') {
            yesClk.apply();
        }
    } else {
        if (noClk && typeof noClk === 'function') {
            noClk.apply();
        }
    }
}

$(function() {
    // 根据配置参数是否隐藏微信内置底部栏
    if (true) {
        wxReady(function() {
            WeixinJSBridge.call('hideToolbar');
        });
    } else {
        wxReady(function() {
            WeixinJSBridge.call('showToolbar');
        });
    }
});

// mini lib
(function() {
    $.kdt = $.kdt || {};
    $.extend($.kdt, {
        getFormData: function($form) {
            var unindexed_array = $form.serializeArray();
            var indexed_array = {};

            $.map(unindexed_array, function(n, i) {
                indexed_array[n['name']] = n['value'];
            });

            return indexed_array;
        },
        spm: function() {
            var spm = $.kdt.getParameterByName('spm');
            if ($.trim(spm) !== '') {
                if (window._global.spm.logType && window._global.spm.logId) {
                    spm += '_' + window._global.spm.logType + window._global.spm.logId;
                }
            } else {
                spm =  '';
            }
            return spm;
        },
        isIOS: function() {
            if (/(iPhone|iPad|iPod)/i.test(navigator.userAgent)) return true;
            return false;
        },
        isAndroid: function() {
            if (/Android/i.test(navigator.userAgent)) return true;
            return false;
        },
        isWeixin: function() {
            $.kdt._weixinEle = $.kdt._weixinEle || $(document.documentElement);
            return $.kdt._weixinEle.hasClass('wx_mobile');
        },
        isMobile: function() {
            return '';
        },
        isWifi: false,
        isCellular: false,
        getParameterByName: function(name) {
            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regexS = "[\\?&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(window.location.search);
            if (results === null)
                return "";
            else
                return decodeURIComponent(results[1].replace(/\+/g, " "));
        },
        removeParameter: function(url, parameter) {
            //prefer to use l.search if you have a location/link object
            var urlparts= url.split('?');
            if (urlparts.length>=2) {

                var prefix= encodeURIComponent(parameter)+'=';
                var pars= urlparts[1].split(/[&;]/g);

                //reverse iteration as may be destructive
                for (var i= pars.length; i-- > 0;) {
                    //idiom for string.startsWith
                    if (pars[i].lastIndexOf(prefix, 0) !== -1) {
                        pars.splice(i, 1);
                    }
                }

                url= urlparts[0]+'?'+pars.join('&');
                return url;
            } else {
                return url;
            }
        },
        addParameter: function(url, obj) {
            var hashArray = url.split('#');
            url = hashArray[0];
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    if ($.trim(obj[key]) === '') {
                        continue;
                    }
                    if (url.indexOf('?') < 0) {
                        url += '?' + $.trim(key) + '=' + $.trim(obj[key]);
                    } else {
                        var para = {};
                        var temp = url.split('?');
                        $.each(temp[1].split('&'), function(index, item) {
                            var arr = item.split('=');
                            if ($.trim(arr[1]) === '') {
                                return;
                            }
                            para[arr[0]] = arr[1];
                        });
                        $.each(obj, function(key, value) {
                            if ($.trim(value) !== '') {
                                para[key] = value;
                            }
                        });

                        var paraArr = [];
                        $.each(para, function(key, value) {
                            paraArr.push(key + '=' + value);
                        });
                        url = temp[0] + '?' + paraArr.join('&');
                    }
                }
            }
            if (hashArray.length === 2) {
                url += '#' + hashArray[1];
            }

            return url;
        },
        log: function(url, cb) {
            var img = new Image(),
                random = Math.floor(Math.random() * 2147483648).toString(36);
            key = 'log_' + random;

            // 这里一定要挂在window下
            // 在IE中，如果没挂在window下，这个img变量又正好被GC的话，img的请求会abort
            // 导致服务器收不到日志
            window[key] = img;

            img.onload = img.onerror = img.onabort = function() {
                // 下面这句非常重要
                // 如果这个img很不幸正好加载了一个存在的资源，又是个gif动画
                // 则在gif动画播放过程中，img会多次触发onload
                // 因此一定要清空
                img.onload = img.onerror = img.onabort = null;

                window[key] = null;

                // 下面这句非常重要
                // new Image创建的是DOM，DOM的事件中形成闭包环引用DOM是典型的内存泄露
                // 因此这里一定要置为null
                img = null;
                // for jQuery Deferred object
                if (cb === Object(cb) && _.isFunction(cb.resolve)) {
                    cb.resolve();
                }
            };

            // 一定要在注册了事件之后再设置src
            // 不然如果图片是读缓存的话，会错过事件处理
            // 最后，对于url最好是添加客户端时间来防止缓存
            // 同时服务器也配合一下传递Cache-Control: no-cache;
            // 2014-04-20  1. not log; 2 change cb status
            //img.src = $.kdt.addParameter(url, {
            //    time: Date.now()
            //});
            if (cb === Object(cb) && _.isFunction(cb.resolve)) {
                cb.resolve();
            }
        },
        getTaobaoModal: function() {
            return $.kdt._taobaoEle = $.kdt._taobaoEle || $('#js-fuck-taobao');
        },
        fuckTaobao: function(url) {
            return ($.kdt.isIOS() || $.kdt.isAndroid()) &&
                $.kdt.isWeixin() &&
                ((url.indexOf('taobao.com') >= 0) ||
                (url.indexOf('tmall.com') >= 0));
        },
        openModal: function() {
            if (!this._opened) {
                if ($.kdt.isIOS()) {
                    $.kdt.getTaobaoModal().find('.js-step-2').addClass('step-2');
                    this._opened = true;
                } else if ($.kdt.isAndroid()) {
                    $.kdt.getTaobaoModal().find('.js-step-2').addClass('step-and-2');
                    this._opened = true;
                }
            }
            $.kdt.getTaobaoModal().removeClass('hide');
        },
        openLink: function(url, newWindow) {
            if (url === void 0 || url === null) {
                return;
            }

            if ($.kdt.fuckTaobao(url)) {
                return $.kdt.openModal();
            };

            newWindow = newWindow || false;
            if (newWindow) {
                var win = window.open(url, '_blank');
                win.focus();
            } else {
                location.href = url;
            }
        },
        parseWeibo: function(url) {
            url = url.toLowerCase();
            var result;
            if (url.indexOf('/showcase/') >= 0) {
                var res = url.match(/\/showcase\/(\w+)\?alias=(\w+)(&|$)/i);
                result = {
                    type: res[1],
                    alias: res[2]
                };
            } else if (url.indexOf('/x/') >= 0) {
                //短地址
                var arr = url.match(/\/x\/(\w+)$/i);
                result = {
                    type: 'x',
                    alias: arr[1]
                };
            }

            return result;
        }
    });
})();

// use Weixin App API to verify user mobile phone's network type
$(function() {
    wxReady(function() {
        WeixinJSBridge.invoke('getNetworkType', {}, function(res) {
            var msg = $.trim(res.err_msg);
            // wifi
            if (msg === 'network_type:wifi') {
                $(document.documentElement).addClass('wifi');
                $.kdt.isWifi = true;
            }
            // 2G/3G
            if (msg === 'network_type:edge' || msg === 'network_type:wwan') {
                $.kdt.isCellular = true;
            }
            /*
             * 统计参数
             */
            var WeixinReadyLog = {
                spm: $.kdt.spm(),
                fm: 'display_network',
                referer_url: encodeURIComponent(document.referrer),
                title: $.trim(document.title),
                msg: encodeURIComponent(msg)
            };
            var pageReadyLogUrl = $.kdt.addParameter(_global.logURL, WeixinReadyLog);
            $.kdt.log(pageReadyLogUrl);
        });
    });
});

//分享
(function() {
    if (document.getElementById('weibo-share-link') !== null) {
        var image = document.getElementsByTagName('img')[0];
        if (image) {
            src = image.src;
        } else {
            src = '';
        }
        var param = {
            url: location.href,
            count: '1',
            /**是否显示分享数，1显示(可选)*/
            appkey: '',
            /**您申请的应用appkey,显示分享来源(可选)*/
            title: document.title || '',
            /**分享的文字内容(可选，默认为所在页面的title)*/
            pic: src,
            /**分享图片的路径(可选)*/
            ralateUid: '',
            /**关联用户的UID，分享微博会@该用户(可选)*/
            language: 'zh_cn' /**设置语言，zh_cn|zh_tw(可选)*/
        };
        var temp = [];
        for (var p in param) {
            temp.push(p + '=' + encodeURIComponent(param[p] || ''));
        }
        var url = 'http://service.weibo.com/share/share.php?' + temp.join('&');
        document.getElementById('weibo-share-link').href = url;
    }
})();
// lazyload
(function($, window, document, undefined) {
    var $window = $(window);

    $.fn.lazyload = function(options) {
        var elements = this;
        var $container;
        var settings = {
            threshold: 0,
            failure_limit: 0,
            event: "scroll",
            effect: "show",
            container: window,
            data_attribute: "src",
            skip_invisible: false,
            appear: null,
            load: null,
            width: null,
            height: null,
            resize: false
        };

        function calculate(objWidth, objHeight) {
            var parentWidth = settings.width,
                parentHeight = settings.height,
                style;

            var resWidth, resHeight;

            var ratio = objHeight / objWidth;

            if (objHeight >= parentHeight && objWidth >= parentWidth) {
                resWidth = parentWidth;
                resHeight = parentWidth * ratio;
                style = {
                    marginTop: (parentHeight - resHeight) / 2
                };
            } else if (objHeight >= parentHeight && objWidth <= parentWidth) {
                style = {
                    marginLeft: (parentWidth - objWidth) / 2,
                    marginTop: (parentHeight - objHeight) / 2
                };
            } else if (objHeight <= parentHeight && objWidth >= parentWidth) {
                resWidth = parentWidth;
                resHeight = parentWidth * ratio;
                style = {
                    marginTop: (parentHeight - resHeight) / 2
                };
            } else if (objHeight <= parentHeight && objWidth <= parentWidth) {
                style = {
                    marginLeft: (parentWidth - objWidth) / 2,
                    marginTop: (parentHeight - objHeight) / 2
                };
            }

            resWidth = resWidth || objWidth;
            resHeight = resHeight || objHeight;

            return {
                width: resWidth,
                height: resHeight,
                style: style
            };
        }

        function update() {
            var counter = 0;

            elements.each(function() {
                var $this = $(this);
                if (settings.skip_invisible && !$this.is(":visible")) {
                    return;
                }
                if ($.abovethetop(this, settings) || $.leftofbegin(this, settings)) {
                    /* Nothing. */
                } else if (!$.belowthefold(this, settings) && !$.rightoffold(this, settings)) {
                    $this.trigger("appear");
                    /* if we found an image we'll load, reset the counter */
                    counter = 0;
                } else {
                    if (++counter > settings.failure_limit) {
                        return false;
                    }
                }
            });

        }

        if (options) {
            /* Maintain BC for a couple of versions. */
            if (undefined !== options.failurelimit) {
                options.failure_limit = options.failurelimit;
                delete options.failurelimit;
            }
            if (undefined !== options.effectspeed) {
                options.effect_speed = options.effectspeed;
                delete options.effectspeed;
            }

            $.extend(settings, options);
        }

        /* Cache container as jQuery as object. */
        $container = (settings.container === undefined || settings.container === window) ? $window : $(settings.container);

        /* Fire one scroll event per scroll. Not one scroll event per image. */
        if (0 === settings.event.indexOf("scroll")) {
            $container.bind(settings.event, function(event) {
                return update();
            });
        }

        this.each(function() {
            var self = this;
            var $self = $(self);

            self.loaded = false;
            $self.parent().addClass('loading');
            /* When appear is triggered load original image. */
            $self.one("appear", function() {
                if (!this.loaded) {
                    if (settings.appear) {
                        var elements_left = elements.length;
                        settings.appear.call(self, elements_left, settings);
                    }
                    $("<img />")
                        .bind("load", function() {
                            if (settings.resize) {
                                var result = calculate(this.width, this.height);
                                $self.hide().attr('src', '').width(result.width).height(result.height).css({
                                    marginLeft: 0,
                                    marginTop: 0
                                }).parent().removeClass('loading');
                                $self.attr('src', $self.data(settings.data_attribute)).css(result.style)[settings.effect](settings.effect_speed);
                            } else {
                                $self.hide()
                                    .attr("src", $self.data(settings.data_attribute))[settings.effect](settings.effect_speed).parent().removeClass('loading');
                            }
                            self.loaded = true;

                            /* Remove image from array so it is not looped next time. */
                            var temp = $.grep(elements, function(element) {
                                return !element.loaded;
                            });
                            elements = $(temp);

                            if (settings.load) {
                                var elements_left = elements.length;
                                settings.load.call(self, elements_left, settings);
                            }


                        })
                        .attr("src", $self.data(settings.data_attribute));
                }
            });

            /* When wanted event is triggered load original image */
            /* by triggering appear. */
            if (0 !== settings.event.indexOf("scroll")) {
                $self.bind(settings.event, function(event) {
                    if (!self.loaded) {
                        $self.trigger("appear");
                    }
                });
            }
        });

        /* Check if something appears when window is resized. */
        $window.bind("resize", function(event) {
            update();
        });

        /* With IOS5 force loading images when navigating with back button. */
        /* Non optimal workaround. */
        if ((/iphone|ipod|ipad.*os 5/gi)
            .test(navigator.appVersion)) {
            $window.bind("pageshow", function(event) {
                if (event.originalEvent.persisted) {
                    elements.each(function() {
                        $(this)
                            .trigger("appear");
                    });
                }
            });
        }

        /* Force initial check if images should appear. */
        $(window)
            .ready(function() {
                update();
            });

        return this;
    };

    /* Convenience methods in jQuery namespace. */
    /* Use as $.belowthefold(element, {threshold : 100, container : window}) */

    $.belowthefold = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.height() + $window.scrollTop();
        } else {
            fold = $(settings.container)
                .offset()
                .top + $(settings.container)
                .height();
        }

        return fold <= $(element)
            .offset()
            .top - settings.threshold;
    };

    $.rightoffold = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.width() + $window.scrollLeft();
        } else {
            fold = $(settings.container)
                .offset()
                .left + $(settings.container)
                .width();
        }

        return fold <= $(element)
            .offset()
            .left - settings.threshold;
    };

    $.abovethetop = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.scrollTop();
        } else {
            fold = $(settings.container)
                .offset()
                .top;
        }

        return fold >= $(element)
            .offset()
            .top + settings.threshold + ($(element)
                .height() || settings.height);
    };

    $.leftofbegin = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.scrollLeft();
        } else {
            fold = $(settings.container)
                .offset()
                .left;
        }

        return fold >= $(element)
            .offset()
            .left + settings.threshold + ($(element)
                .width() || settings.width);
    };

    $.inviewport = function(element, settings) {
        return !$.rightoffold(element, settings) && !$.leftofbegin(element, settings) && !$.belowthefold(element, settings) && !$.abovethetop(element, settings);
    };

})($, window, document);

// 统计
(function() {
    var spm = $.kdt.spm();
    /**
     * 点击统计
     */
    $.kdt.clickLogHandler = function(e) {
        var $this = $(this);
        var url = $this.attr('href'),
            newWindow = $this.attr('target') === '_blank',
            clickID = $this.data('goods-id'),
            title = $this.prop('title') || $this.text();

        if ($.trim(url) === '' || $.trim(url).indexOf('javascript') === 0 || $this.hasClass('js-no-follow')) {
            return;
        }

        /**
         * 站内地址添加spm参数
         * 兼容老的beacon
         */
        var targetURL = url;
        if (url.match(/^https?:\/\/\S*\.?(koudaitong\.com|kdt\.im)/)) {
            targetURL = $.kdt.addParameter(url, {
                spm: spm
            });
        }

        newLog();

        function newLog() {
            /**
             * 站外地址先发送统计
             */
            var deferred = $.Deferred().done(function() {
                if ($.kdt.isMobile() || !newWindow) {
                    $.kdt.openLink(targetURL);
                }
            });
            var params = {
                spm: spm,
                fm: 'click',
                url: window.encodeURIComponent(url),
                referer_url: encodeURIComponent(document.referrer),
                title: $.trim(title)
            }
            if (e.fromMenu) {
                $.extend(params, {
                    click_type: 'menu'
                });
            }
            if (clickID !== null && clickID !== void 0) {
                $.extend(params, {
                    click_id: clickID
                });
            }
            var _logUrl = $.kdt.addParameter(_global.logURL, params);
            $.kdt.log(_logUrl, deferred);
        }

        if ($.kdt.isMobile() || !newWindow) {
            e.preventDefault();
        } else {
            // 替换统计地址
            $this.attr('href', targetURL);
        }
    }
    $(document).on('click', 'a', $.kdt.clickLogHandler);
    var displayGoods = (function() {
        var arr = [];
        var $goodsList = $('.js-goods');
        if ($goodsList.length < 1) {
            return null;
        }
        $goodsList.each(function(index, item) {
            var $item = $(item);
            arr.push($item.data('goods-id'));
        });

        return arr.join(',');
    })();
    /*
     * 统计参数
     */
    var pageReadyLogConfig = {
        spm: spm,
        fm: 'display',
        referer_url: encodeURIComponent(document.referrer),
        title: $.trim(document.title)
    };
    if (displayGoods) {
        $.extend(pageReadyLogConfig, {
            display_goods: displayGoods
        });
    }
    /**
     * 页面ready时候发送页面展现的统计
     */
 /*   var pageReadyLogUrl = $.kdt.addParameter(_global.logURL, pageReadyLogConfig);
    $.kdt.log(pageReadyLogUrl);*/

    /**
     * Lazyload
     */
    $('.js-lazy').lazyload({
        threshold: 100
    });
    /**
     * 商品封面图片lazyload以及展现日志统计
     */
    $('.js-goods-lazy').lazyload({
        threshold: 100,
        /**
         * 商品展现发送展现统计
         */
        appear: function() {
            var id = $(this).parents('.js-goods').first().data('goods-id');
            var str;
            if (spm.lastIndexOf('_') === spm.length - 1) {
                str = spm + 'SI' + id;
            } else {
                str = spm + '_SI' + id;
            }
      /*      $.kdt.log($.kdt.addParameter(_global.logURL, {
                spm: str,
                fm: 'display',
                referer_url: encodeURIComponent(document.referrer)
            }));*/
        }
    });

    // if ($('.js-share').length) {
    //     var shareTooltip = $('.js-share-tooltip');
    //     $(document).on('click', '.js-share', function(e) {
    //         var that = $(this);
    //         if (shareTooltip.hasClass('in')) {
    //             that.removeClass('tip_animate');
    //             shareTooltip.removeClass('in');
    //         } else {
    //             that.addClass('tip_animate');
    //             shareTooltip.addClass('in');
    //         }

    //         e.preventDefault();
    //     });
    // }

    // 非粉丝顶部显示商家微信公众号信息
    var rootEle = $(document.documentElement);
    var mpInfo = $('.js-mp-info');
    var followGuide = $('#js-follow-guide');

    mpInfo.on('click', '.js-follow-mp', function(event) {
        followGuide.removeClass('hide');
        return false;
    });
    followGuide.on('click', '.js-close-guide', function(event) {
        followGuide.addClass('hide');
        return false;
    });
    followGuide.find('.wxid').on('click', function(event) {
        event.stopPropagation();
    });
    $(document).on('click', '#js-follow-guide', function(event) {
        followGuide.addClass('hide');
        return false;
    });


    // 轮播
    $('.custom-image-swiper').each(function(index, item) {
        var $item = $(item);
        var container = $item.find('.swiper-container');
        var pagination = $item.find('.swiper-pagination');
        var config = {
            mode: 'horizontal',
            pagination: pagination[0],
            paginationClickable: true,
            calculateHeight: true,
            autoplay: 3500,
            onSlideChangeStart: function(swiper) {
                var $imgs = $item.find('.js-slide-lazy'),
                    index = swiper.activeIndex;
                $imgs.eq(index).trigger('appear');
                $imgs.eq(index + 1).trigger('appear');
            },
            onTouchStart: function(swiper) {
                swiper.stopAutoplay();
            },
            onTouchEnd: function(swiper) {
                swiper.startAutoplay();
            }
        };
        if (container.find('.swiper-slide').length > 1) {
            if ($('.content').width() >= 540) {
                $.extend(config, {
                    slidesPerView: 1.5
                });
            }
            
            //console.log(JSON.stringify(config, censor(config)));
            var mySwiper = new Swiper(container[0], config);
        };
    });
    $('.js-slide-lazy').lazyload({
        threshold: 100
    });

    var ua = window.navigator.userAgent;
    var wxVer = ua.match(/MicroMessenger\/(\d+(\.\d+)*)/);

    function reviewImage(src) {
        if (typeof window.WeixinJSBridge != 'undefined') {
            WeixinJSBridge.invoke('imagePreview', {
                'current': src,
                'urls': imgsSrc
            });
        }
    }

    // 仅在微信浏览器中处理图片
    if (wxVer !== null && wxVer.length) {
        var imgs = $('.js-image-swiper img, .custom-richtext img'),
            imgsSrc = [],
            minWidth = 0;

        imgs.each(function() {
            var img = $(this),
                src = img.attr('data-src') || img.attr('src');
            if (img.width() >= minWidth && src) {
                if (img.parents('a').length > 0) {
                    return;
                }
                imgsSrc.push(src);
                img.on('click', function() {
                    reviewImage(src);
                });
            }
        });
    }

})($, window, document);


// fuck taobao
(function() {
    $.kdt.getTaobaoModal().on('touchstart', function(e) {
        var $tar = $(e.target);
        if (e.target.className.indexOf('step-') < 0) {
            $.kdt.getTaobaoModal().addClass('hide');
        }
    });
})();

// 店铺导航
(function() {
    // 元素固定
    var elemFixed = function(options) {
        var opts = $.extend({
            element: '', // （*必填）要固定的目标元素
            footer: '', // （*必填）底部元素
            margin_footer: 0, // 目标元素与底部元素的距离（可以是正数 / 负数）
            margin_top: 0, // 目标元素初始与窗口顶部的距离（本来用 $elem.position().top 可以获取到该值，不过有些特殊场合取值不准，可以通过设置此值来解决）
            fixed_top: 0 // 目标元素固定时与窗口顶部的距离
        }, options)

        var $elem = $(opts.element),
            $ft = $(opts.footer),
            elem_top = opts.margin_top ? opts.margin_top : $elem.position().top,
            elem_height = $elem.height(),
            win_height = $(window).height(),
            ft_top = $ft.position().top - opts.margin_footer;
        $(window).scroll(function() {
            var win_top = $(this).scrollTop(),
                // $ft 离窗口顶部距离
                foot_margin_top = ft_top - win_top;

            if (win_top > elem_top && elem_height < win_height) {
                $elem.css({
                    position: "fixed",
                    // 避免固定元素叠在 $ft 上
                    top: (foot_margin_top < elem_height) ? (foot_margin_top - elem_height) : opts.fixed_top
                });
            } else {
                $elem.css("position", "relative");
            }
        });
    };

    var shopNav = {
        // 显示二级导航
        showSubmenu: function(e) {
            var $target = $(e.target),
                $one = $target.parents('.one'),
                $mainmenu = $target.hasClass('.js-mainmenu') ? $target : $one.find('.js-mainmenu'),
                $submenu = $one.find('.js-submenu'),
                $arrow = $submenu.find('.arrow'),
                $menu = $target.parents('.js-navmenu'),
                $ones = $menu.find('.one'),
                menuLength = $ones.length,
                index = $ones.index($one),
                mainMenuLength = $mainmenu.outerWidth(),
                mainLength = ($submenu.outerWidth() - $mainmenu.outerWidth()) / 2,
                subLength = $submenu.outerWidth() / 2;

            if ($submenu.size() === 0) {
                $('.js-submenu:visible').hide();
            } else {
                var subMenuWidth = $submenu.outerWidth(),
                    mainMenuWidth = $one.outerWidth();

                var subLeft = 'auto',
                    arrowLeft = 'auto',
                    subRight = 'auto',
                    arrowRight = 'auto';

                if (index === 0) {
                    subLeft = $mainmenu.position().left - mainLength;
                    arrowLeft = subLength - ($arrow.outerWidth() / 2);
                } else if (index === menuLength - 1) {
                    if (subMenuWidth > mainMenuWidth) {
                        subRight = 8;
                        arrowRight = mainMenuLength / 2 - subRight;
                    } else {
                        subLeft = $mainmenu.position().left - mainLength;
                        arrowLeft = subLength - ($arrow.outerWidth() / 2);
                    }
                } else {
                    subLeft = $mainmenu.position().left - mainLength;
                    arrowLeft = subLength - ($arrow.outerWidth() / 2);
                }

                var SIDE_PADDING = 5;
                if (subLeft < 0) {
                    arrowLeft = arrowLeft + subLeft + SIDE_PADDING;
                    subLeft = SIDE_PADDING;
                }

                if (subRight < 0) {
                    arrowRight = arrowRight + subRight + SIDE_PADDING;
                    subRight = SIDE_PADDING;
                }

                $submenu.css({
                    left: subLeft,
                    right: subRight
                });
                $arrow.css({
                    left: arrowLeft,
                    right: arrowRight
                });
                $('.js-submenu:visible').not($submenu).hide();
                $submenu.toggle();
            }
        },
        // 显示顶部菜单
        openNavmenu: function(e) {
            var $navmenu = $('.js-navmenu');
            $navmenu.slideToggle('fast');
            //$navmenu.toggle();
            $('.js-submenu:visible').hide();
            $('.js-open-navmenu .caret').toggleClass('up-arrow');
            e.stopPropagation();
        }
    };
    if ($.kdt.isMobile()) {
        // 隐藏菜单
        $(document).on('touchstart', function() {
            // 注意：hide()要加时间参数，否则当导航为nav-on-top-hide时，点击body不会让子菜单消失，会有残影
            $('.js-submenu:visible').hide(0);
            // 折叠的导航
            // $('.nav-on-top-hide').slideUp('fast');
            $('.js-open-navmenu .caret').removeClass('up-arrow');
        });
        // 点击主菜单条
        $('body').on('touchstart', '.js-navmenu', function(e) {
            e.fromMenu = true;
            $.kdt.clickLogHandler.call(e.target, e);
            e.stopPropagation();
        });
        // 点击子菜单
        $('body').on('touchstart', '.js-submenu', function(e) {
            e.fromMenu = true;
            $.kdt.clickLogHandler.call(e.target, e);
            e.stopPropagation();
        });
        // 显示子菜单
        $('body').on('touchstart', '.js-mainmenu', function(e) {
            shopNav.showSubmenu(e);
        });
        // 显示主菜单
        $('body').on('touchstart', '.js-open-navmenu', function(e) {
            shopNav.openNavmenu(e);
        });
    } else {
        // 隐藏菜单
        $(document).on('click', function() {
            // 注意：hide()要加时间参数，否则当导航为nav-on-top-hide时，点击body不会让子菜单消失，会有残影
            $('.js-submenu:visible').hide(0);
            // 折叠的导航
            // $('.nav-on-top-hide').slideUp('fast');
            $('.js-open-navmenu .caret').removeClass('up-arrow');
        });
        // 点击主菜单条
        $('body').on('click', '.js-navmenu', function(e) {
            e.fromMenu = true;
            $.kdt.clickLogHandler.call(e.target, e);
            e.stopPropagation();
        });
        // 点击子菜单
        $('body').on('click', '.js-submenu', function(e) {
            e.fromMenu = true;
            $.kdt.clickLogHandler.call(e.target, e);
            e.stopPropagation();
        });
        // 显示子菜单
        $('body').on('click', '.js-mainmenu', function(e) {
            shopNav.showSubmenu(e);
        });
        // 显示主菜单
        $('body').on('click', '.js-open-navmenu', function(e) {
            shopNav.openNavmenu(e);
        });
    }
    // 底部导航悬浮
    var navBottomElem = '.nav-on-bottom',
        $paginationElem = $('.js-custom-paginations');
    if (($(navBottomElem).size() + $paginationElem.size()) > 0) {
        $('body').css('padding-bottom', $('.js-navmenu').height() || $paginationElem.height());
    }
})();

// 会员模块
(function() {
    var $levels = $('.js-custom-level'),
        $points = $('.js-custom-point'),
        $section = $('.js-custom-level-title-section');

  /*  if (_global.fans_id <= 0) {
        return;
    }*/

    var url ='';/* window._global.url.wap + '/showcase/component/fans.jsonp?' + $.param({
        kdt_id: window._global.kdt_id
    });*/

    if ($levels.length > 0 || $points.length > 0) {
        $.ajax({
            dataType: 'jsonp',
            type: 'GET',
            url: url,
            success: function(resp) {
                if (resp.code == 0) {
                    $levels.html(resp.data.level || '会员');
                    $points.html(resp.data.point || '暂无数据');
                    $section.removeClass('hide');
                }
            }
        });
    }
})();

// 登录弹出层
(function() {
    var $login = $('.js-modal-login');
    $.extend($.kdt, {
        login: function(callback) {
            if ($login.length <= 0) {
                return;
            }
            $login.addClass('active');
            if (_.isFunction(callback)) {
                $.kdt._loginCB = callback;
            }
        }
    });

    var formEle = $('.js-login-form'),
        postUrl = formEle.attr('action'),
        loginPwdTxt = formEle.find('.js-login-pwd'),
        submitBtn = formEle.find('.js-submit-butn'),
        loginTitle = $login.find('.js-login-title span'),
        forgetEle = $login.find('.js-forget-password'),
        modeToggler = $login.find('.js-login-mode');

    formEle.on('blur', '.js-login-phone', function() {
        var ele = $(this);

        var phone = $.trim(ele.val());
        var oldLink = forgetEle.attr('href'),
            newLink;

        phone = (/^1\d{10}$/).test(phone) ? phone : '';

        if ((/^1\d{10}$/).test(phone)) {
            newLink = $.kdt.addParameter(oldLink, {
                'phone': phone
            });
        } else {
            newLink = $.kdt.removeParameter(oldLink, 'phone');
        }

        forgetEle.attr('href', newLink);
    });

    formEle.on('click', '.js-login-cancel', function() {
        // helpInfo.empty();
        if ($login.length > 0) {
            $login.removeClass('active');
        } else {
            window.history.back();
        }
    });

    formEle.on('click', '.js-login-mode', function() {
        var ele = $(this);

        var mode = ele.data('login-mode');
        if (mode === 'signin') {
            loginTitle.html('请先登录');
            ele.html('(注册)');
            loginPwdTxt.attr('placeholder', '请填写您的密码');
            ele.data('login-mode', 'signup');
        } else {
            loginTitle.html('请先注册');
            ele.html('(登录)');
            loginPwdTxt.attr('placeholder', '请设置您的密码');
            ele.data('login-mode', 'signin');
        }
    });

    //登录提交
    formEle.on('submit', function(event) {
        event.preventDefault();

        var postData = $.kdt.getFormData(formEle);

        postData.mode = modeToggler.data('login-mode');

        if (!validForm(postData)) {
            return false;
        }
  
        $.ajax({
            url: postUrl,
            type: 'post',
            dataType: 'json',
            timeout: 15000,
            data: postData,
            beforeSend: function() {
                submitBtn.html('登录中...');
                submitBtn.prop('disabled', true);
            },
            success: function(resp) {
                var code = resp.code;

                if (code === 0) {

                    if ($.kdt._loginCB) {
                    	
                        $.kdt._loginCB();
                    }
                    $login.removeClass('active');
               
                    if (window._global && window._global.redirect_url) {
                    
                        var url = $.kdt.addParameter(window._global.redirect_url, { kdt_sso_token: resp.data.kdt_sso_token });
                        window.location.assign(url);
                    } else {
                        window._global.kdt_sso_token = resp.data.kdt_sso_token;
                    }

                    motify.clear();
                    // helpInfo.empty();
                } else {

                    motify.log(resp.msg);
                    // helpInfo.addClass('error').html(resp.msg);

                }
            },
            error: function(xhr, errorType, error) {
            	alert(error)
                motify.log('出错啦，请重试');
                // helpInfo.html('出错啦，请重试');
            }
        }).always(function() {
            submitBtn.html('下一步');
            submitBtn.prop('disabled', false);
        });
    });

    function validForm(postData) {
        if (postData.phone === '') {
            formEle.find('input[name="phone"]').focus();
            motify.log('请填写您的手机号码');
            // helpInfo.addClass('error').html('请填写您的手机号码');
            return false;
        }
        if (!(/^1\d{10}$/).test(postData.phone)) {
            formEle.find('input[name="phone"]').focus();
            motify.log('请填写11位手机号码');
            // helpInfo.addClass('error').html('请填写11位手机号码');
            return false;
        }
        if (postData.password === '') {
            formEle.find('input[name="password"]').focus();
            motify.log('麻烦输入一下您的密码吧');
            // helpInfo.addClass('error').html('麻烦输入一下您的密码吧');
            return false;
        }
        if (postData.password.length > 16) {
            formEle.find('input[name="password"]').focus();
            motify.log('亲，密码太长了，怕您记不住，还是短一点啦');
            // helpInfo.addClass('error').html('亲，密码太长了，怕您记不住，还是短一点啦');
            return false;
        }
        return true;
    }
})();
// tpl-weixin模板动画
(function() {
    var $weixinItem = $('.js-tpl-weixin-list-item'),
        $weixinBgImg = $('.js-tpl-weixin-bg');

    if ($weixinBgImg.length <= 0) {
        return;
    }

    var weixinBgImg = $weixinBgImg[0];

    var weixinTimeout = setTimeout(function() {
        handler();
    }, 2000);

    function handler() {
        clearTimeout(weixinTimeout)
        $weixinItem.addClass('done');
    }

    weixinBgImg.onload = weixinBgImg.onerror = weixinBgImg.onabort = handler;
    if (weixinBgImg.complete) {
        handler();
    }
})();


function censor(censor) {
	var i = 0;

	return function(key, value) {
		if (i !== 0 && typeof (censor) === 'object'
				&& typeof (value) == 'object' && censor == value)
			return '[Circular]';

		if (i >= 29) // seems to be a harded maximum of 30 serialized objects?
			return '[Unknown]';

		++i; // so we know we aren't using the original object anymore

		return value;
	}
}



$(function(){
	
	
	$("#myOrder-ljg").click(function(){
		
		if(window.loginstatus==0){
			
		window.location.href='/index.php?r=buyer';
			
		}else{
			
			window.location.href='/index.php?r=buyer/user_center';
			
		};
		
	});
	
	
})